﻿using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Drawing;
using XBLib.Dal.AdoDal; 

public partial class Org_frmO_EmpDiplomaInput : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ((Org_MasterPage)this.Master).changeTitle("保有資格情報登録");
        ((Org_MasterPage)this.Master).HideLiArea("frmO_EmpDiplomaInput");

		if (Session["人コード"] == null)
		{
			Response.Redirect("../frmD_Login.aspx");
		}
		else if (Session["人コード"].ToString() == "")
		{
			Response.Redirect("../frmD_Login.aspx");
		}

		if (Request.UrlReferrer != null)
		{
			string PageRequest = Request.UrlReferrer.ToString();

			if (PageRequest.IndexOf("frmO_EmpLangAbilityInput.aspx") > 0 || PageRequest.IndexOf("frmO_EmpWorkSkillInput.aspx") > 0)
			{
				if (Session["社員ID"] == null || Session["企業コード_2"] == null)
					Response.Redirect("../frm_MainMenu.aspx");
				else if (Session["社員ID"].ToString() == "" || Session["企業コード_2"].ToString() == "")
					Response.Redirect("../frm_MainMenu.aspx");

				Session["Action_frmO_EmpDiplomaInput"] = "insert";
			}
			if (PageRequest.IndexOf("frmO_EmpBasicInfo.aspx") > 0)
			{
				Session["Action_frmO_EmpDiplomaInput"] = "update";
				btn_次.Visible = false;
			}
		}
		else {
			if (Session["Action_frmO_EmpDiplomaInput"] != null && Session["Action_frmO_EmpDiplomaInput"].ToString() == "update")
				Response.Redirect("frmO_EmpBasicInfo.aspx");
		}

		try
		{
			string id = "";
			string id2 = "";

			if (Session["Action_frmO_EmpDiplomaInput"].ToString() == "update")
			{
				id = Request.QueryString["id"] != null ? Request.QueryString["id"] : "";
				ViewState["保有資格情報_社員ID"] = Int32.Parse(id);

				id2 = Request.QueryString["id2"] != null ? Request.QueryString["id2"] : "";
				ViewState["保有資格情報ID"] = id2 != "" ? Int32.Parse(id2) : 0;
			}
			else
			{
				ViewState["保有資格情報_社員ID"] = Int32.Parse(Session["社員ID"].ToString());
			}
		}
		catch
		{
			Response.Redirect("frmO_EmpBasicInfo.aspx");
		}

        if (!IsPostBack)
        {
            bind資格免許();
            bind社内外区分();
            ddl_資格免許.Focus();

			int 社員ID = Int32.Parse(ViewState["保有資格情報_社員ID"].ToString());
			
			if (Session["役"] != null && Session["役"].ToString() != "1")
				CheckExist社員ID(社員ID);

			LoadGrv保有資格情報一覧(社員ID);

            string ER00007 = GetError("ER00007");
            string ER00006 = GetError("ER00006");
            string ER00005 = GetError("ER00005");
            string ER00001 = GetError("ER00001");

            RequiredFieldValidator資格免許.ErrorMessage = ER00007;
            RequiredFieldValidator社内外区分.ErrorMessage = ER00007;
            CustomValidator受検年月日.ErrorMessage = ER00005;
            CustomValidator受検年月日1.ErrorMessage = ER00006;
            RequiredFieldValidator受検年月日.ErrorMessage = ER00001;
            CustomValidator取得年月日.ErrorMessage = ER00005;
            CustomValidator取得年月日1.ErrorMessage = ER00006;
			CustomValidator取得年月日2.ErrorMessage = ER00005;
            RequiredFieldValidator取得年月日.ErrorMessage = ER00001;

			if (Session["Action_frmO_EmpDiplomaInput"].ToString() == "update")
				LoadInfo_Reset保有資格情報(社員ID);
        }
    }
	protected void CheckExist社員ID(int 社員ID)
	{
		int Result = -1;
		int 企業ID = Int32.Parse(Session["企業コード_2"].ToString());
		保有資格情報Manager frm = new 保有資格情報Manager();
		frm.CheckExist社員ID_frmO_EmpDiplomaInput(企業ID, 社員ID, out Result);
		if (Result == 0)
		{
			Response.Redirect("frmO_EmpList.aspx");
		}
	}
	protected void LoadInfo_Reset保有資格情報(int 社員ID)
	{
		保有資格情報Manager frm = new 保有資格情報Manager();
		int ID2 = Int32.Parse(ViewState["保有資格情報ID"].ToString());
		if (ID2 != 0)
		{
			DataTable dt = frm.SelectInfo保有資格情報_ByID(ID2, 社員ID);
			if (dt.Rows.Count > 0)
			{
				ddl_資格免許.SelectedValue = dt.Rows[0]["資格免許コード"].ToString();
				ddl_社内外区分.SelectedValue = Boolean.Parse(dt.Rows[0]["社内外区分"].ToString()) == true ? "1" : "0";
				txt_受検年月日.Text = DateTime.Parse(dt.Rows[0]["受検年月日"].ToString()).ToString("yyyy/MM/dd");
				txt_取得年月日.Text = DateTime.Parse(dt.Rows[0]["取得年月日"].ToString()).ToString("yyyy/MM/dd");

				btn登録.Text = "更新";
				Session["Action_frmO_EmpDiplomaInput"] = "update";
			}
			else
			{
				Response.Redirect("frmO_Emplist.aspx");
			}
		}
		else
		{
			btn登録.Text = "登録";
			Label 資格免許 = (Label)grv_保有資格情報一覧.Rows[0].FindControl("lbl_資格免許");
			if (資格免許 == null)
			{
				AppCode_Common.ShowEmtyGrid<保有資格情報>(grv_保有資格情報一覧, 3, "データがありません。", "");
			}
		}
	}
    protected void btn_戻る_Click(object sender, EventArgs e)
    {
		if (btn_次.Visible == false)
			Response.Redirect("frmO_EmpBasicInfo.aspx?id=" + ViewState["保有資格情報_社員ID"].ToString() + "#120");
		else
			Response.Redirect("frmO_EmpLangAbilityInput.aspx");
    }
    protected void btn_次_Click(object sender, EventArgs e)
    {
		Response.Redirect("frmO_EmpWorkSkillInput.aspx");
    }
	protected void LoadGrv保有資格情報一覧(int 社員ID)
	{
		保有資格情報Manager frm = new 保有資格情報Manager();
		DataTable dt = frm.SelectData保有資格情報(社員ID);
		if (dt.Rows.Count > 0)
		{
			grv_保有資格情報一覧.DataSource = dt;
			grv_保有資格情報一覧.DataBind();

			ViewState["CurrentTable"] = dt;
		}
		else
		{
			AppCode_Common.ShowEmtyGrid<保有資格情報>(grv_保有資格情報一覧, 3, "データがありません。", "");
		}
	}

    /// <summary>
    /// load du lieu vao dropdownList 資格免許
    /// </summary>
    public void bind資格免許()
    {
        保有資格情報Manager frm = new 保有資格情報Manager();
        DataTable dt = frm.Select資格免許();
        ddl_資格免許.DataSource = dt;
        ddl_資格免許.DataTextField = "資格免許名";
        ddl_資格免許.DataValueField = "ID";
        ddl_資格免許.DataBind();

        ListItem 選択 = new ListItem("[選択]", "-1");
        ddl_資格免許.Items.Insert(0, 選択);
    }

    /// <summary>
    /// load du lieu dropdownList 社内外区分
    /// </summary>
    public void bind社内外区分()
    {
        try
        {
            DataTable dt = new DataTable();
            DataColumn col;
            DataRow row;

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.Int32");
            col.ColumnName = "value";
            dt.Columns.Add(col);

            col = new DataColumn();
            col.DataType = System.Type.GetType("System.String");
            col.ColumnName = "text";
            dt.Columns.Add(col);

            row = dt.NewRow();
            row["value"] = -1;
            row["text"] = "[選択]";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["value"] = 0;
            row["text"] = "社内";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["value"] = 1;
            row["text"] = "社外";
            dt.Rows.Add(row);

            ddl_社内外区分.DataSource = dt;
            ddl_社内外区分.DataValueField = "value";
            ddl_社内外区分.DataTextField = "text";

            ddl_社内外区分.DataBind();
        }
        catch { }
    }
    protected void btnリセット_Click(object sender, EventArgs e)
    {
		ViewState["RowID_Color"] = "";
		ResetForm();
    }
    protected void btn登録_Click(object sender, EventArgs e)
    {
        bool isValidate = true;

        SetValueForControl();

        if (isValidate == true)
        {
            保有資格情報 obj = new 保有資格情報();
            obj.廃止区分 = 0;
            obj.資格免許コード = ddl_資格免許.SelectedValue;
            obj.資格免許名 = ddl_資格免許.SelectedItem.Text;
            obj.社内外区分 = ddl_社内外区分.SelectedValue == "1" ? true : false;
            obj.受検年月日 = DateTime.Parse(txt_受検年月日.Text);
            obj.取得年月日 = DateTime.Parse(txt_取得年月日.Text);
			obj.社員ID = Int32.Parse(ViewState["保有資格情報_社員ID"].ToString());

            保有資格情報Manager frm = new 保有資格情報Manager();

			if (btn登録.Text == "登録")
			{
				ViewState["RowID_Color"] = frm.Insert保有資格情報(obj);
				ViewState["Row_Class_Name"] = "insert";
			}
			else
			{
				int 保有資格情報ID = 0;

				if (ViewState["保有資格情報_GrvID"] != null)
					保有資格情報ID = Int32.Parse(ViewState["保有資格情報_GrvID"].ToString());
				else
					保有資格情報ID = Int32.Parse(ViewState["保有資格情報ID"].ToString());

				ViewState["RowID_Color"] = 保有資格情報ID.ToString();
				ViewState["Row_Class_Name"] = "update";

				frm.UpdateInfo保有資格情報_ByID(obj, 保有資格情報ID);
			}

			ViewState["保有資格情報_GrvID"] = ViewState["RowID_Color"];
			ResetForm();
			ViewState.Remove("保有資格情報_GrvID");
			ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "aReady();", true);
        }
    }

	protected void ResetForm()
	{
		int 社員ID = Int32.Parse(ViewState["保有資格情報_社員ID"].ToString());
		if (Request.QueryString["id2"] != null)
		{
			LoadInfo_Reset保有資格情報(社員ID);
		}
		else
		{
			ddl_資格免許.SelectedValue = "-1";
			ddl_社内外区分.SelectedValue = "-1";
			txt_取得年月日.Text = "";
			txt_受検年月日.Text = "";
			btn登録.Text = "登録";
		}

		LoadGrv保有資格情報一覧(社員ID);
	}
    
    /// <summary>
    /// ham lay loi tu database
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    public String GetError(string errorid)
    {
        string error = "";
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        if (dt.Rows.Count > 0)
            error = dt.Rows[0][2].ToString();
        return error;
    }

    /// <summary>
    /// chuyen doi ki tu < >
    /// </summary>
    /// <param name="root"></param>
    /// <returns></returns>
    public static Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }
    protected void SetValueForControl()
    {
        Control[] allControls = FlattenHierachy(Page);
        foreach (Control control in allControls)
        {
            TextBox textBox = control as TextBox;
            if (textBox != null)
            {
                textBox.Text = textBox.Text.Replace("<", "&lt;");
                textBox.Text = textBox.Text.Replace(">", "&gt;");
            }
        }
    }

	protected void grv_保有資格情報一覧_PreRender(object sender, EventArgs e)
	{
		if (ViewState["Row_Class_Name"] != null)
		{
			string class_name = ViewState["Row_Class_Name"].ToString();
			for (int i = 0; i < grv_保有資格情報一覧.Rows.Count; i++)
			{
				string grv_id = grv_保有資格情報一覧.DataKeys[i].Value.ToString();
				string compare_id = (string)ViewState["RowID_Color"];
				if (grv_id == compare_id)
				{
					grv_保有資格情報一覧.Rows[i].CssClass = class_name;
				}
			}
		}
	}

	protected void grv_保有資格情報一覧_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		try
		{
			if (e.CommandName.Equals("LoadUpdate"))
			{
				int index = grv_保有資格情報一覧.Rows[Convert.ToInt32(e.CommandArgument)].DataItemIndex;
				DataTable dt = (DataTable)ViewState["CurrentTable"];

				ddl_資格免許.SelectedValue = dt.Rows[index]["資格免許コード"].ToString();
				ddl_社内外区分.SelectedValue = Boolean.Parse(dt.Rows[index]["社内外区分"].ToString()) == true ? "1" : "0";
				txt_受検年月日.Text = DateTime.Parse(dt.Rows[index]["受検年月日"].ToString()).ToString("yyyy/MM/dd");
				txt_取得年月日.Text = DateTime.Parse(dt.Rows[index]["取得年月日"].ToString()).ToString("yyyy/MM/dd");

				btn登録.Text = "更新";

				ViewState["保有資格情報_GrvID"] = dt.Rows[index]["ID"].ToString();
			}
		}
		catch (Exception ex)
		{
			Response.Write(ex.StackTrace);
		}

		ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "aReady();", true);
	}

	protected void grv_保有資格情報一覧_SelectedIndexChanging(object sender, GridViewPageEventArgs e)
	{
		grv_保有資格情報一覧.PageIndex = e.NewPageIndex;
		int 社員ID = Int32.Parse(ViewState["保有資格情報_社員ID"].ToString());
		LoadGrv保有資格情報一覧(社員ID);
		ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "aReady();", true);
	}

	protected void grv_保有資格情報一覧_RowDataBound(object sender, GridViewRowEventArgs e)
	{
		if (e.Row.RowType == DataControlRowType.DataRow)
		{
			e.Row.Attributes.Add("onclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv_保有資格情報一覧','LoadUpdate$" + e.Row.RowIndex + "')");
		}
	}
}
